package com.by_man.presenter.module_health_records.upload_health_records;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.presenter.module_health_records.image.BitmapManager;
import com.by_man.presenter.module_health_records.image.ImageInfo;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.UserInfos;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by man on 2017-02-25.
 */
public class UploadHealthRecordsActivity extends AppCompatActivity {
    private PopupWindow popupWindow;
    private GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_health_records);
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_upload_health_records, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.putExtra("position", 2);
//                startActivity(intent);        // 不能使用这种写法
                onBackPressed();
                break;
            case R.id.send:
                if (BitmapManager.images.size() == 0) {
                    SharedApplication.showToast(this, "请先选择图片上传");
                } else {
                    AsyncHttpClient client = new AsyncHttpClient();
                    for (int i=0; i < BitmapManager.images.size(); i++) {
                        String imgPath = BitmapManager.images.get(i).imagePath;
                        File imgFile = new File(imgPath);
                        if (imgFile.exists() && imgFile.length() > 0) {
                            RequestParams params = new RequestParams();
                            params.put("token", UserInfos.token);
                            try {
                                final String fileKey = "uploadFile" + i;
                                params.put(fileKey, imgFile);
                                client.post(IpAddress.Upload_File, params, new AsyncHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(int statusCode, Header[] headers, String response) {
                                        Log.i("UploadHealthRecords", response);
                                    }

                                    @Override
                                    public void onFailure(int statusCode, Header[] headers, byte[] response, Throwable error) {
                                        Log.i("UploadHealthRecordError", error.getMessage());
                                        Toast.makeText(UploadHealthRecordsActivity.this, "上传图片" + fileKey + "失败！",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } catch (FileNotFoundException fe) {
                                fe.printStackTrace();
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.putExtra("position", 2);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

    protected void onRestart()
    {
        super.onRestart();
        adapter.notifyDataSetChanged();
    }

    private void showPopupWindow(boolean show) {
        if (show)
            popupWindow.showAsDropDown(findViewById(R.id.root));
        else
            popupWindow.dismiss();
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        toolbar.setNavigationIcon(R.drawable.icon_back);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        gridView = (GridView) findViewById(R.id.noScrollgridview);

        // 设置
        Context mContext = getApplicationContext();
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
        View menuView = inflater.inflate(R.layout.upload_health_records_popupwindows, null);
        // 浮动菜单
        popupWindow = new PopupWindow(menuView,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        // Set an elevation value for popup window
        // Call requires API level 21
        if(Build.VERSION.SDK_INT>=21){
            popupWindow.setElevation(5.0f);
        }
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(menuView);

        Button takePhotoBtn = (Button) menuView.findViewById(R.id.item_popupwindows_camera);
        Button chosePhotoBtn = (Button) menuView.findViewById(R.id.item_popupwindows_Photo);
        Button cancelBtn = (Button) menuView.findViewById(R.id.item_popupwindows_cancel);

        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(false);
                takePhoto();            // 调用相机
            }
        });
//
        chosePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(false);
                Intent intent = new Intent(UploadHealthRecordsActivity.this, ChosePhotoActivity.class);
                startActivity(intent);
            }
        });
//
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(false);
            }
        });

        // 为GridView设定adapter
        adapter = new GridViewAdapter();
        gridView.setAdapter(adapter);
        // 为GridView注册监听
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == BitmapManager.images.size()) {
                    showPopupWindow(true);
                } else {
                    Intent intent = new Intent(UploadHealthRecordsActivity.this, PhotoGalleryActivity.class);
                    startActivity(intent);
                }
            }
        });
    }
    private GridViewAdapter adapter;
    private static final int TAKE_PICTURE = 0x000001;
    private File pthotopath;
    // 调用相机的服务
    private void takePhoto() {
        /*
        * 设置URI，指定相册拍照后保存图片的路径，Uri imageUri = Uri.fromFile(new File(imagePath, "image.jsp"));
           openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        * */
        String fa=String.valueOf(System.currentTimeMillis())+ ".PNG";
        File photoPath = new File(Environment.getExternalStorageDirectory()+ "/Photo_MR");
        // 判断文件夹是否已经存在
        if(!photoPath.exists()) photoPath.mkdirs();
        pthotopath = new File(Environment.getExternalStorageDirectory()
                + "/Photo_MR",fa);
        Uri imageU= Uri.fromFile(pthotopath);
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageU);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                // 将图片信息添加到BitmapManager中
                if (BitmapManager.images.size() < BitmapManager.max && resultCode == RESULT_OK) {
                    ImageInfo info = new ImageInfo();
                    info.imagePath = String.valueOf(pthotopath);
                    BitmapManager.images.add(info);
                    adapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(popupWindow != null) {
            popupWindow.dismiss();

            popupWindow = null;
        }
    }

    // 这块逻辑很混乱需要后续更改

    // GirdView 的自定义adapter

    private class GridViewAdapter extends BaseAdapter {
        public int getCount() {
            if (9 == BitmapManager.images.size()) {
                return BitmapManager.images.size();
            } else {
                return BitmapManager.images.size()+1;
            }
        }

        public Object getItem(int position) {
            return null;
        }
        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView img;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_health_records_grid_view, parent, false);
                img = (ImageView) convertView.findViewById(R.id.item_grida_image);
                convertView.setTag(img);
            } else {
                img = (ImageView) convertView.getTag();
            }

            if (position == BitmapManager.images.size()) {
                img.setImageResource(R.drawable.icon_addpic_unfocused);
                if (position == 9) img.setVisibility(View.GONE);
            } else {
                loadBitmap(position, img);
            }
            return convertView;
        }
    }

    // 封装ImageView与异步加载任务的关联关系
    private class AsyncInfo {
        private int position;
        private final WeakReference<AsyncImageLoader> imageLoaderWeakReference;

        public AsyncInfo(int position, AsyncImageLoader imageLoader) {
            this.position = position;
            imageLoaderWeakReference = new WeakReference<AsyncImageLoader>(imageLoader);
        }

        public AsyncImageLoader getAsyncImageLoader() {
            return imageLoaderWeakReference.get();
        }
    }

    // 异步加载图片
    private class AsyncImageLoader extends AsyncTask<Integer, Void, Bitmap> {
        private final WeakReference<ImageView> imageViewWeakReference;
        public AsyncImageLoader(ImageView imageView) {
            imageViewWeakReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        protected Bitmap doInBackground(Integer...params){
             int position = params[0];
            String imgPath = BitmapManager.images.get(position).imagePath;
            String thumbnailPath = BitmapManager.images.get(position).thumbnailPath;
            Bitmap bitmap;
            if (thumbnailPath == null) {
                bitmap = BitmapManager.getCompressBitmap(imgPath,100,100);
            } else {
                bitmap = BitmapManager.getCompressBitmap(thumbnailPath, 100, 100);
                // 可能不存在略缩图,所以加上此判断防止出现空指针异常
                if (null == bitmap) {
                    bitmap = BitmapManager.getCompressBitmap(imgPath,100,100);
                }
            }
            BitmapManager.putBitmap(imgPath, bitmap);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (imageViewWeakReference != null && bitmap != null) {
                ImageView imageView = imageViewWeakReference.get();
                imageView.setImageBitmap(bitmap);
            }
        }

    }

    public AsyncImageLoader getAsyncImageLoader(ImageView imageView) {
        if (imageView != null) {
            AsyncInfo a = (AsyncInfo) imageView.getTag();
            if (a != null) {
                return a.getAsyncImageLoader();
            }
        }
        return null;
    }

    public boolean cancelAsyncWork(int positon, ImageView imageView) {
         AsyncInfo a = (AsyncInfo) imageView.getTag();
        if (a != null) {
            if (a.position != positon) {
                AsyncImageLoader imageLoader = a.getAsyncImageLoader();
                imageLoader.cancel(true);
            } else {
                return false;
            }
        }
        return true;
    }

    public void loadBitmap(int p, ImageView imageView) {
        if (cancelAsyncWork(p,imageView)) {     // 取消任务成功，重新创建任务
            String imgPath = BitmapManager.images.get(p).imagePath;
            Bitmap bitmap = BitmapManager.getBitmap(imgPath);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                // 创建加载任务
                AsyncImageLoader imageLoader = new AsyncImageLoader(imageView);
                AsyncInfo asyncInfo = new AsyncInfo(p, imageLoader);
                imageView.setTag(asyncInfo);
                imageView.setImageResource(R.drawable.plugin_camera_no_pictures);
                imageLoader.execute(p);
            }
        }
    }

}
